#!/usr/bin/env python

from __future__ import with_statement

import model
import threading

class Groups(object):
    '''Groups class
    
    @author Julot <andy.julot@gmail.com>
    @since Wednesday, February 29, 2012. 09:46 AM'''
    
    def __init__(self, view, interactor):
        self.view = view
        self.interactor = interactor
        
        self.populate()
    
    def populate(self):
        self.view.busyCursor()
        with threading.RLock():
            groups = model.Group.objects.query().order_by('name')
            self.view.groups.group.models = groups
        self.view.idle()
        
    def filter(self, value):
        self.view.busyCursor()
        pattern = r'\b%s\b' % value
        members = model.Contact.objects.query().order_by('name')
        members.filter(groups__regexp=pattern)
        
        others = model.Contact.objects.query().order_by('name')
        if members:
            others.filter(groups__notregexp=pattern)
        self.view.groups.members.models = members
        self.view.groups.contacts.models = others
        self.view.idle()